package service

import (
	"context"
	"fmt"
	"gitee.com/crack007/goose"
	"github.com/crack007/go-im/pb"
	"github.com/crack007/go-im/src/common/model"
	"google.golang.org/grpc"
	"time"
)

type grpcService struct {
	nodeMap map[string]*grpc.ClientConn
}

func (s *grpcService) SendMsg(nodeModel *model.NodeModel, messageModel *model.MessageModel) error {
	target := fmt.Sprintf("%s:%d", nodeModel.Ip, nodeModel.Port)
	goose.GetLogger().Debug("SendMsg target->%s", target)
	var err error
	var conn *grpc.ClientConn
	var ok bool
	if conn, ok = s.nodeMap[target]; !ok {
		conn, err = grpc.Dial(target, grpc.WithInsecure(), grpc.WithBlock())
		if err != nil {
			return err
		}
		s.nodeMap[target] = conn
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	messageServiceClient := pb.NewNodeServiceClient(conn)
	_, err = messageServiceClient.SendUserMsg(ctx, &pb.UserMsg{
		Data:        messageModel.Data,
		FromNode:    messageModel.FromNode,
		FromUser:    messageModel.FromUser,
		ToUser:      messageModel.ToUser,
		MessageType: uint32(messageModel.MessageType),
		CreatedAt:   messageModel.CreatedAt,
		MsgId:       messageModel.MsgId,
		Action:      messageModel.Action,
	})
	return err
}
